package org.haifi.game.reflection;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Locale;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.haifi.game.GameException;
import org.haifi.game.GameString;
import org.haifi.game.annotation.GString;
import org.haifi.game.util.ResourceUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.opensymphony.xwork2.util.LocalizedTextUtil;

/**
 * 从language.xls中读取语种相关的内容，然后置入代码
 * 
 * TODO:需要验证一下这种方式，能从war包读出配置文件不
 * 
 * @author joycube2
 * 
 */
@Component
@Lazy(false)
public class XlsLanguageUtil {

	@PostConstruct
	public void initLanguageResouces() {
		try {
			String locale = ResourceUtil.getText("game.locale");
			if (locale == null) {
				// 在这里获取不到，可能是因为加载的比webapp更早
				LocalizedTextUtil.addDefaultResourceBundle("game");
				locale = ResourceUtil.getText("game.locale");
			}
			ResourceUtil.locale = new Locale(locale);

			String xlsName = "language.xls";
			InputStream inputStream = Thread.currentThread()
					.getContextClassLoader().getResourceAsStream(
							"xls/" + xlsName);
			POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);
			HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);

			// 处理异常
			processSheet(workbook, "exception", GameException.class, locale);
			// 处理游戏中的字符串
			processSheet(workbook, "string", GameString.class, locale);

		} catch (Exception e) {
			log.error("ERROR", e);
		}
	}

	private void processSheet(HSSFWorkbook workbook, String sheetName,
			Class clazz, String locale) throws Exception {
		HSSFSheet sheet = workbook.getSheet(sheetName);

		String[] titles = parseCell(sheet.getRow(0));

		List<String[]> allDatas = Lists.newArrayList();
		for (int m = 1; m <= sheet.getLastRowNum(); m++) {
			String[] data = parseCell(sheet.getRow(m));
			allDatas.add(data);
		}

		int index = 0;
		for (int m = 0; m < titles.length; m++) {
			String title = titles[m];
			if (locale.equals(title)) {
				index = m;
				break;
			}
		}

		for (Field field : clazz.getFields()) {
			GString error = field.getAnnotation(GString.class);
			if (error != null) {
				String key = field.getName();
				boolean exists = false;
				for (String[] data : allDatas) {
					if (key.equals(data[0])) {
						field.set(clazz, data[index]);
						exists = true;
						break;
					}
				}
				if (!exists) {
					log.error("字段未翻译:" + key);
				}
			}
		}
	}

	private String[] parseCell(HSSFRow row) {
		String[] results = new String[row.getLastCellNum()];
		for (int m = 0; m < results.length; m++) {
			results[m] = parseCellText(row, m);
		}
		return results;
	}

	private String parseCellText(HSSFRow row, int cellNum) {
		String text = "";
		HSSFCell cell = row.getCell(cellNum);
		text = cell.getStringCellValue();
		return text;
	}

	private final Log log = LogFactory.getLog(getClass());
}
